package controleur;

import beans.CliClients;
import beans.Livre;
import beans.Panier;
import java.io.IOException;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import traitements.AfficherCompte;
import traitements.Commande;
import traitements.Connexion;
import traitements.GererLivre;

@WebServlet(name = "ctrl", urlPatterns = {"/ctrl/*"})
public class Controler extends HttpServlet {

    public static final String ATT_CLIENT = "client";
    public static final String ATT_FORM = "form";
    public static final String ATT_ADR = "adresses";
    public static final String ATT_PHO = "phones";
    private static Panier panier = new Panier();

    protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        request.setCharacterEncoding("UTF-8");

        HttpSession session = request.getSession();

        /* Section Login - switch */
        Cookie cookiePresent = getCookie(request, ATT_CLIENT);

        if ((cookiePresent != null) && (request.getParameter("action").equals("home"))) {
            Connexion con = new Connexion();
            CliClients client = con.autoConnect(Integer.parseInt(cookiePresent.getValue()));
            session.setAttribute(ATT_CLIENT, client);
            this.getServletContext().getRequestDispatcher("/WEB-INF/welcome.jsp").forward(request, response);
        }

        if ((cookiePresent != null) && (request.getParameter("action").equals("bye"))) {
            session.setAttribute(ATT_CLIENT, null);
            cookiePresent.setValue("");
            cookiePresent.setMaxAge(0);
            response.addCookie(cookiePresent);
            this.getServletContext().getRequestDispatcher("/WEB-INF/welcome.jsp").forward(request, response);
        }
        if ((cookiePresent == null) && (request.getParameter("action").equals("home"))) {

            this.getServletContext().getRequestDispatcher("/WEB-INF/welcome.jsp").forward(request, response);
        }
        if (request.getParameter("action").equals("connect")) {
            this.getServletContext().getRequestDispatcher("/WEB-INF/login.jsp").forward(request, response);

        }

        if (request.getParameter("action").equals("bye")) {
            session.setAttribute(ATT_CLIENT, null);
            if (cookiePresent != null) {
                cookiePresent.setValue(null);
                cookiePresent.setMaxAge(0);
            }
            this.getServletContext().getRequestDispatcher("/WEB-INF/welcome.jsp").include(request, response);
        }

        if (request.getParameter("action").equals("connexion")) {
            Connexion con = new Connexion();
            CliClients client = con.ConnecterCli(request);
            request.setAttribute(ATT_CLIENT, client);
            request.setAttribute(ATT_FORM, con);
            Cookie compteur = getCookie(request, "compteur");
            if (compteur == null) {
                compteur = new Cookie("compteur", "1");
            }
            if (con.getErreurs().isEmpty()) {
                /* Si aucune erreur */
                if (request.getParameter("cc") != null) {
                    Cookie cc = new Cookie(ATT_CLIENT, "" + client.getCliId());
                    cc.setMaxAge(60 * 60);
                    response.addCookie(cc);
                }
                compteur.setValue("1");
                compteur.setMaxAge(0);
                response.addCookie(compteur);
                session.setAttribute(ATT_CLIENT, client);
                this.getServletContext().getRequestDispatcher("/WEB-INF/welcome.jsp").forward(request, response);
            } else {
                /* Sinon ré-affichage du formulaire avec les erreurs */
                session.setAttribute(ATT_CLIENT, null);
                int i = Integer.parseInt(compteur.getValue());
                compteur.setValue(++i + "");
                if (i > 3) {
                    request.setAttribute("tentative", true);
                }
                compteur.setMaxAge(3 * 60);
                response.addCookie(compteur);
                this.getServletContext().getRequestDispatcher("/WEB-INF/login.jsp").forward(request, response);
            }
        }

        if (request.getParameter("action").equals("voircompte")) {
            CliClients client = (CliClients) session.getAttribute(ATT_CLIENT);
            AfficherCompte tmp = new AfficherCompte();
            if (client != null) {
                ArrayList listeAdr = tmp.getAdresses(client.getCliId());
                ArrayList listePhones = tmp.getPhones(client.getCliId());
                session.setAttribute(ATT_ADR, listeAdr);
                session.setAttribute(ATT_PHO, listePhones);
            }
            this.getServletContext().getRequestDispatcher("/WEB-INF/affichagecompte.jsp").forward(request, response);
        }

        /* Section Panier */
        if (request.getParameter("action").equals("cata") && (request.getParameter("ref") != null)) {
            panier.add(request.getParameter("ref"));
            session.setAttribute("contenu", panier.nbProduit());
            session.setAttribute("panier", panier);
            request.setAttribute("nbpages", request.getAttribute("nbres"));
            request.setAttribute("page", request.getAttribute("page"));
            this.getServletContext().getRequestDispatcher("/WEB-INF/catalogue.jsp").include(request, response);
        }


        /* Section CATALOGUE*/
        if (request.getParameter("action").equals("cata")) {
            int page = 1;
            int ligpage = 5;
            int nbpages = 0;
            GererLivre tmp;
            try {
                tmp = new GererLivre();
                int nbLivres = tmp.getNbLivres();

                page = Integer.parseInt(request.getParameter("page"));
                if ((request.getParameter("nbres") != null) && (!(request.getParameter("nbres").equals("")))) {
                    ligpage = Integer.parseInt(request.getParameter("nbres"));
                }
                nbpages = (int) Math.ceil(nbLivres * 1.0 / ligpage);
                ArrayList<Livre> listing;
                if ((page - 1) * ligpage < nbLivres) {
                    listing = tmp.getPgLivres((page - 1) * ligpage, ligpage);
                } else {
                    listing = tmp.getPgLivres(nbLivres - ligpage, ligpage);
                    page = nbpages;
                }

                request.setAttribute("listing", listing);
                request.setAttribute("nbpages", nbpages);
                request.setAttribute("page", page);
                session.setAttribute("nbres", ligpage);
                this.getServletContext().getRequestDispatcher("/WEB-INF/catalogue.jsp").forward(request, response);

            } catch (ClassNotFoundException ex) {
                Logger.getLogger(Controler.class.getName()).log(Level.SEVERE, null, ex);
            } catch (SQLException ex) {
                Logger.getLogger(Controler.class.getName()).log(Level.SEVERE, null, ex);
            }
        }

        if (request.getParameter("action").equals("detaillivre")) {

            GererLivre tmp;
            try {
                tmp = new GererLivre();
                Livre livre = tmp.afficherLivre(Integer.valueOf(request.getParameter("livreid")));
                request.setAttribute("detaillivre", livre);
            } catch (ClassNotFoundException ex) {
                Logger.getLogger(Controler.class.getName()).log(Level.SEVERE, null, ex);
            } catch (SQLException ex) {
                Logger.getLogger(Controler.class.getName()).log(Level.SEVERE, null, ex);
            }

            this.getServletContext().getRequestDispatcher("/WEB-INF/detaillivre.jsp").forward(request, response);
        }

        /*Historique des commandes*/

        CliClients client = (CliClients) session.getAttribute(ATT_CLIENT);

        if ("vueCommande".equals(request.getParameter("action"))) {
            if (session.getAttribute(ATT_CLIENT) == null) {
                request.setAttribute("connected", false);
                getServletContext().getRequestDispatcher("/WEB-INF/vueCommande.jsp").include(request, response);
            } else {
                request.setAttribute("connected", true);
                Commande mesCommandes = (Commande) session.getAttribute("myCommandes");
                if (mesCommandes == null) {
                    mesCommandes = new Commande();
                    session.setAttribute("myCommandes", mesCommandes);
                }

                request.setAttribute("lesCommandes", mesCommandes.listeCommandes(client.getCliId()));
                getServletContext().getRequestDispatcher("/WEB-INF/vueCommande.jsp").include(request, response);
            }
        }

        if ("vueDetailCmde".equals(request.getParameter("action"))) {
            Commande mesCommandes = (Commande) session.getAttribute("myDetailCommandes");
            if (mesCommandes == null) {
                mesCommandes = new Commande();
                session.setAttribute("myDetailCommandes", mesCommandes);
            }
            request.setAttribute("leDetailCommandes", mesCommandes.detailCommandes());
            this.getServletContext().getRequestDispatcher("/WEB-INF/vueDetailCmde.jsp").forward(request, response);
        }

        /* Section footer - pages générales */
        if (request.getParameter("action").equals("cgv")) {
            this.getServletContext().getRequestDispatcher("/WEB-INF/cgv.jsp").forward(request, response);
        }
        if (request.getParameter("action").equals("legal")) {
            this.getServletContext().getRequestDispatcher("/WEB-INF/legal.jsp").forward(request, response);
        }
        if (request.getParameter("action").equals("faq")) {
            this.getServletContext().getRequestDispatcher("/WEB-INF/faq.jsp").forward(request, response);
        }
        if (request.getParameter("action").equals("contact")) {
            this.getServletContext().getRequestDispatcher("/WEB-INF/contact.jsp").forward(request, response);
        }
    }

    /**
     * Méthode utilitaire gérant la récupération de la valeur d'un cookie donné
     * depuis la requête HTTP.
     */
    private static Cookie getCookie(HttpServletRequest request, String nom) {
        Cookie[] cookies = request.getCookies();
        if (cookies != null) {
            for (Cookie cookie : cookies) {
                if (cookie != null && nom.equals(cookie.getName())) {
                    return cookie;
                }
            }
        }
        return null;
    }

// <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /**
     * Handles the HTTP
     * <code>GET</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /**
     * Handles the HTTP
     * <code>POST</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /**
     * Returns a short description of the servlet.
     *
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>
}